﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using SyncLib;
using SyncLib.Client;
using System.Configuration;
using SyncLib.Interface;
using System.Data;
using SyncApplication.Business;
using System.Threading;
using System.IO;
using log4net;

namespace SyncApplication
{
    static class Program
    {
        static ILog Log = LogManager.GetLogger(typeof(Log4NetImplement));
        static Mutex singleApp;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            singleApp = new Mutex(false, "SyncClient");
            //if (!AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe"))
            {
                Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            }
            if (!singleApp.WaitOne(1000))
            {
                MessageBox.Show("Chương trình đã chạy! Vui lòng kiểm tra lại");
                return;
            }
            try
            {


                log4net.Config.XmlConfigurator.Configure();
                ClientSyncContext.SyncDS = new ClientSyncDS();
                LoadAppConfig();     
                
                Application.Run(new FrmNotify());
                //Application.Run(new Test());

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                singleApp.ReleaseMutex();
            }
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Log.Fatal("*********************************************************");
            Log.Fatal("Lỗi rồi", e.Exception);
            Log.Fatal("*********************************************************");
           // SyncDialog.Current.TraceInfo();
        }

        private static void CheckBatchFolder()
        {
            if (!string.IsNullOrEmpty(CommonVariable.SyncFolderBatch))
            {
                if (!Directory.Exists(CommonVariable.SyncFolderBatch))
                {
                    Directory.CreateDirectory(CommonVariable.SyncFolderBatch);
                }
            }
        }

        public static void LoadAppConfig()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (ConfigurationManager.AppSettings["TokenSecur"] == null)
            {

                config.AppSettings.Settings.Add("TokenSecur", AuthenticationHandle.Encode("administrator", "nothing", "nothing"));
                config.Save(ConfigurationSaveMode.Full);

            }
            
            string[] tempv = AuthenticationHandle.Decode(config.AppSettings.Settings["TokenSecur"].Value);
            CommonVariable.Add("UserName", tempv[0]);
            CommonVariable.Add("Password", tempv[1]);

            CommonVariable.SqlConnectionString = ConfigurationManager.AppSettings[ClientConst.SK_SqlConnectionString];
            CommonVariable.SyncConfigSchema = "dbo";
            CommonVariable.SyncFolderBatch = ConfigurationManager.AppSettings[ClientConst.SK_BatchFolder];
            CommonVariable.CleanBatch=bool.Parse(ConfigurationManager.AppSettings[ClientConst.SK_CleanBatch]);
            CheckBatchFolder();
            CommonVariable.AppLocation = (AppLocation)Enum.Parse(typeof(AppLocation), ConfigurationManager.AppSettings["AppLocaltion"]);

            string urlProvidetType = ConfigurationManager.AppSettings[ClientConst.SK_UrlProvider];
            Type t = Type.GetType(urlProvidetType);
            ClientSyncContext.UrlProvider = (IUrlProvider)Activator.CreateInstance(t);
            ClientSyncContext.CreateProxyPerTask = bool.Parse(ConfigurationManager.AppSettings["CreateProxyPerTask"]);

            if (ConfigurationManager.AppSettings[ClientConst.ClientID] == "")
            {
                ConfigurationManager.AppSettings[ClientConst.ClientID] = Guid.Empty.ToString();
            }
            //ClientId
            try
            {
                CommonVariable.Add(ClientConst.ClientID, new Guid(ConfigurationManager.AppSettings[ClientConst.ClientID]));
                object temp = SqlHelper.ExecuteScalar(CommonVariable.SqlConnectionString, CommandType.Text, "Select ISNULL(ClientName,N'Không rõ') FROM Client where ClientId='" + ConfigurationManager.AppSettings[ClientConst.ClientID] + "'");
                if (temp != DBNull.Value && temp != null)
                    CommonVariable.Add("ClientName", temp.ToString());
                else
                    CommonVariable.Add("ClientName", "Không rõ");
            }
            catch { }

            SyncDialog.ShowWhenSync = bool.Parse(ConfigurationManager.AppSettings["ShowMonitorForm"]);
            if(FrmNotify.Current!=null)
            FrmNotify.Current.RefreshRunMode();
            

        }
    }
}
